package com.geekstudy.week7;

import java.sql.*;

public class Week7Work10 {

    private Connection readConnection;

    private Connection writeConnection;

    public ResultSet select(String sql) throws SQLException {
        if(readConnection == null) {
            String url = "jdbc:mysql://127.0.0.1:3306/geek_java4";
            String username = "java4read";
            String password = "java4read";
            readConnection = DriverManager.getConnection(url, username, password);
        }

        Statement statement = readConnection.createStatement();
        ResultSet resultSet = statement.executeQuery(sql);
       // statement.close();
        return resultSet;
    }

    public boolean insert(String sql) throws SQLException {
        if(writeConnection == null) {
            String url = "jdbc:mysql://127.0.0.1:3306/geek_java4";
            String username = "java4";
            String password = "java4";
            writeConnection = DriverManager.getConnection(url, username, password);
        }
        Statement statement = writeConnection.createStatement();
        boolean result = statement.execute(sql);
        return result;
    }

    public static void main(String[] args) {

        try {
            Week7Work10 week7Work10 = new Week7Work10();


            String insertSql = "insert into geek_study(id, name, nick_name, address)  "
                    + "values ('" + System.currentTimeMillis() +  "', 'Name week10_1', 'NickName week10-1', 'Address Week 10-1') ";
            boolean insertResult = week7Work10.insert(insertSql);
            System.out.println(" insert result:" + insertResult);

            String querySql = "select count(id) as num from geek_study";
            ResultSet resultSet = week7Work10.select(querySql);
            int queryNum = -1;
            if(resultSet.next()) {
                queryNum = resultSet.getInt("num");
            }
            System.out.println(" select num:" + queryNum);

            week7Work10.readConnection.createStatement().execute(insertSql);

        } catch(Exception e) {
            e.printStackTrace();
        }


    }

}
